<template>
    <div class="jira-tab-wrap">
        <div class="page-wrap">
            <filter-form class="margin-b-8" :disabled="loading || disabled" :detail="detail" :isSync="isSync" @search="handleSearch">
                <template #extra>
                    <flexbox v-if="showHandleBtn">
                        <a-button type="primary" @click="handleBack" v-if="isSync">返回</a-button>
                        <flexbox v-else>
                            <a-button :disabled="loading || disabled" @click="handleSyncManage">同步管理</a-button>
                            <a-button type="primary" :disabled="loading || disabled" class="margin-l-8" @click="getIssuseList">获取issue</a-button>
                        </flexbox>
                    </flexbox>
                </template>
            </filter-form>
            <flexbox justify="flex-end" class="margin-t-8">
                <flexbox style="flex: 1" v-if="isSync && selectedRowKeys.length">
                    <span>已选中{{ selectedRowKeys.length }}项</span>
                    <a-button type="primary" class="margin-l-8" @click="handleCreateMulti" :disabled="!showMultiCreateBtn">同步新增产品需求</a-button>
                </flexbox>
                <span class="margin-b-8 caption-font-color" v-if="list.length"> 上一次更新：{{ detail.pullTime }} </span>
            </flexbox>
            <custom-table rowKey="id" size="small" :loading="loadingObj" :columns="tableColumns" :data-source="list" v-bind="bindTableProps" :pagination="paginationConfig" @change="handleTableChange">
                <template #status="{ record }">
                    <a-tag color="blue" v-if="record.status === '进行中'"> {{ record.status }}</a-tag>
                    <a-tag color="success" v-else-if="record.status === '已完成'"> {{ record.status }}</a-tag>
                    <a-tag color="default" v-else> {{ record.status }}</a-tag>
                </template>
                <template #action="{ record, index }">
                    <div v-if="isSync" style="display: inline-block">
                        <a @click="handleCreate(index)" v-if="record.syncStatus === '未同步'">同步新建</a>
                        <a @click="handleRelate(index)" v-if="record.syncStatus === '重复'">同步关联</a>
                        <a @click="handleUpdate(index)" v-if="record.syncStatus === '已同步'">同步更新</a>
                    </div>
                    <a @click="showDetail(record.jiraUrl)" v-else>详情</a>
                </template>
            </custom-table>
            <update-modal ref="updateModalRef" :systemId="detail.id" />
        </div>
    </div>
</template>

<script lang="ts">
import FilterForm from './components/filterForm.vue';
import api from '@/api';
import store from '@/store';
import { CustomTable } from '@/components';
import UpdateModal from './components/updateModal.vue';
import { useTableData, useTableLoading, usePagination, useTableRowSelect } from '@/components/Table/hooks/index';
import { useSyncRequest } from '@/hooks/common/useSyncRequest';
import { computed, defineComponent, ref, unref, getCurrentInstance } from 'vue';
import { message } from 'ant-design-vue';
export default defineComponent({
    components: {
        FilterForm,
        CustomTable,
        UpdateModal
    },
    props: {
        detail: { type: Object, default: () => ({}) }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const { list, getList, handleTableChange, setSearchQuery } = useTableData(setLoading, paginationConfig, setPaginationConfig, 'jiraIssue');
        const { selectedRowKeys, selectedRows, onSelectChange } = useTableRowSelect();
        const { loadingObj, syncDataFromJira } = useSyncRequest(loading, setLoading, emit);
        const bindTableProps = ref<any>({});
        const isSync = ref<boolean>(false);
        const updateModalRef = ref<any>();
        const disabled = ref<boolean>(false);
        const showHandleBtn = computed(() => {
            const instance: any = getCurrentInstance();
            let arr: any = [];
            if (props.detail.pmpSystemManagers['需求管理员']) {
                arr = [...props.detail.pmpSystemManagers['产品经理'], ...props.detail.pmpSystemManagers['需求管理员']];
            } else {
                arr = [...props.detail.pmpSystemManagers['产品经理']];
            }
            let res = arr.find((item) => item.empId === store.getters.userInfo.employeeDTO.empId);
            res = !!res || instance.proxy.userInfo.roles.includes('admin');
            return res;
        });
        const showMultiCreateBtn = computed(() => {
            return unref(selectedRows).every((item) => item.syncStatus === '未同步');
        });
        const tableColumns = computed(() => {
            let columns: any = [];
            if (unref(isSync)) {
                columns = [
                    {
                        title: '类型',
                        dataIndex: 'issueType'
                    },
                    {
                        title: '关键字',
                        dataIndex: 'issueKey'
                    },
                    {
                        title: '摘要',
                        dataIndex: 'summary',
                        width: 400,
                        ellipsis: true
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        slots: { customRender: 'status' }
                    },
                    {
                        title: '同步状态',
                        dataIndex: 'syncStatus'
                    },
                    {
                        title: '对应数据',
                        dataIndex: 'requireNumber',
                        width: 200,
                        ellipsis: true
                    },
                    {
                        title: '对应数据名称',
                        dataIndex: 'requireName',
                        width: 200,
                        ellipsis: true
                    },
                    {
                        title: '版本名称',
                        dataIndex: 'fixVersion'
                    },
                    {
                        title: '操作',
                        dataIndex: '',
                        key: 'action',
                        fixed: 'right',
                        slots: { customRender: 'action' }
                    }
                ];
            } else {
                columns = [
                    {
                        title: '类型',
                        dataIndex: 'issueType'
                    },
                    {
                        title: '关键字',
                        dataIndex: 'issueKey'
                    },
                    {
                        title: '摘要',
                        dataIndex: 'summary',
                        width: 400,
                        ellipsis: true
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        slots: { customRender: 'status' }
                    },
                    {
                        title: '经办人',
                        dataIndex: 'assigneeName'
                    },
                    {
                        title: '解决结果',
                        dataIndex: 'resolution'
                    },
                    {
                        title: '版本名称',
                        dataIndex: 'fixVersion'
                    },
                    {
                        title: 'sprint',
                        dataIndex: 'sprint',
                        width: 300
                    },
                    {
                        title: '操作',
                        dataIndex: '',
                        key: 'action',
                        fixed: 'right',
                        slots: { customRender: 'action' }
                    }
                ];
            }
            return columns;
        });
        const getIssuseList = () => {
            const fn = () => {
                setSearchQuery({
                    systemId: props.detail.id
                });
                getList();
            };
            syncDataFromJira(
                api.jiraModel.syncIssueFromJira,
                {
                    systemId: props.detail.id
                },
                fn
            );
        };
        const handleSearch = (query) => {
            setSearchQuery({
                ...query,
                systemId: props.detail.id
            });
            getList();
            onSelectChange([], []);
        };
        const handleSyncManage = () => {
            const fn = () => {
                isSync.value = true;
                bindTableProps.value = {
                    'row-selection': { selectedRowKeys, onChange: onSelectChange }
                };
                setSearchQuery({
                    systemId: props.detail.id
                });
                getList().then(({ success, totalCount }) => {
                    success && message.success(`本次同步数据${totalCount}条`);
                });
            };
            syncDataFromJira(
                api.jiraModel.syncIssueFromJira,
                {
                    systemId: props.detail.id
                },
                fn
            );
        };
        //同步新建
        const handleCreate = async (index: number) => {
            const { success, moule, errorMsg } = await api.jiraModel.createProductFromJira([{ ...list.value[index], systemId: props.detail.id }]);
            if (success) {
                message.success('创建成功');
                list.value[index] = { ...moule[0] };
            } else {
                message.error(errorMsg);
            }
        };
        const handleCreateMulti = async () => {
            const list = unref(selectedRows).map((item) => ({
                ...item,
                systemId: props.detail.id
            }));
            const { success, errorMsg } = await api.jiraModel.createProductFromJira([...list]);
            if (success) {
                message.success('创建成功');
                getList();
                onSelectChange([], []);
            } else {
                message.error(errorMsg);
            }
        };
        const handleRelate = async (index: number) => {
            const { success, moule, errorMsg } = await api.jiraModel.connectProductFromJira({ ...list.value[index], systemId: props.detail.id });
            if (success) {
                message.success('关联成功');
                list.value[index] = { ...moule };
            } else {
                message.error(errorMsg);
            }
        };
        const handleUpdate = async (index: number) => {
            unref(updateModalRef).open(list.value[index]);
        };
        const showDetail = (url) => {
            window.open(url, '_blank');
        };
        const handleBack = () => {
            isSync.value = false;
            if (Reflect.has(bindTableProps.value, 'row-selection')) {
                Reflect.deleteProperty(bindTableProps.value, 'row-selection');
            }
        };
        const init = () => {
            setSearchQuery({
                systemId: props.detail.id
            });
            getList().then((res) => {
                disabled.value = !res.success;
            });
        };
        init();
        return {
            updateModalRef,
            bindTableProps,
            showHandleBtn,
            disabled,
            showMultiCreateBtn,
            list,
            isSync,
            paginationConfig,
            selectedRowKeys,
            loading,
            tableColumns,
            getIssuseList,
            showDetail,
            handleTableChange,
            handleSearch,
            handleSyncManage,
            handleCreate,
            handleCreateMulti,
            handleRelate,
            handleUpdate,
            handleBack,

            loadingObj
        };
    }
});
</script>
<style scoped lang="less">
.jira-tab-wrap {
    padding: 24px 0 0 0;
    background: #f0f2f5;
    .page-wrap {
        min-height: 400px;
        padding: 24px;
        background: #fff;
    }
}
</style>